//
//  YHPromiseManager.swift
//  SwiftProject
//
//  Created by qindong on 2021/4/6.
//

import UIKit
import AssetsLibrary

class PromiseManager: NSObject, CLLocationManagerDelegate {

    let locationManager : CLLocationManager = CLLocationManager()
    
    static var shared = PromiseManager()
    
    private override init() {
        
    }
    
    func getAlwaysLocationPermissions(_ always : Bool, _ completion : ((_ success : Bool)->Void)? = nil) {
        if !CLLocationManager.locationServicesEnabled() {
            if completion != nil {
                completion!(false)
            }
        }
        locationManager.delegate = self
        
        let status = CLLocationManager.authorizationStatus()
        DispatchQueue.global().async {
            if status.rawValue < 3 && status.rawValue > 0 {
                if completion != nil {
                    completion!(false)
                }
            } else if status == .notDetermined {
                if always {
                    self.locationManager.requestAlwaysAuthorization()
                } else {
                    self.locationManager.requestWhenInUseAuthorization()
                }
                if completion != nil {
                    completion!(true)
                }
            } else {
                if always {
                    if status == .authorizedAlways {
                        
                    }
                }
                if completion != nil {
                    completion!(true)
                }
            }
        }
    }
    
    func getCameraPermissionsCompletion(_ completion : ((_ success : Bool)->Void)? = nil) {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        if status == .denied || status == .restricted {
            if completion != nil {
                completion!(false)
            }
        }
        if completion != nil {
            completion!(true)
        }
    }
    
    func getAlbumPermissionCompletion(_ completion : ((_ success : Bool)->Void)? = nil) {
        let status = PHPhotoLibrary.authorizationStatus()
        if status == .denied || status == .restricted {
            if completion != nil {
                completion!(false)
            }
        }
        if completion != nil {
            completion!(true)
        }
    }
}


